﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mabalacat.CPS.BusinessLogic.Services.Interfaces;
using Mabalacat.CPS.DataAccess.DataObjects;
using System.Data.Entity;
using Mabalacat.CPS.DataAccess.Repositories;
using Mabalacat.CPS.DataAccess.Base;

namespace Mabalacat.CPS.BusinessLogic.Services
{
    public class SignatoryService : ISignatoryService
    {

        #region Fields

        private DbContext _dbContext;
        private ISignatoryRepository _signatoryRepository;        
        private IDatabaseFactory _dbFactory;
        #endregion

        #region ctor

        public SignatoryService()
            : this(new DatabaseFactory())
        {

        }

        public SignatoryService(IDatabaseFactory dbFactory)
        {
            if (dbFactory == null) throw new ArgumentNullException("dbFactory");
            _dbFactory = dbFactory;
            DbContext = dbFactory.Get();
        }

        private DbContext DbContext
        {
            get { return _dbContext; }
            set
            {
                _dbContext = value;
                _signatoryRepository = new  SignatoryRepository(_dbContext);                
            }
        }

        #endregion

        public Signatory GetById(int id)
        {
            return _signatoryRepository.GetById(id);
        }

        public Signatory GetDefault()
        {
            var defaultRecord = _signatoryRepository.GetQuery().FirstOrDefault();
            if (defaultRecord == null)
            {
                defaultRecord = new Signatory();
                this.Add(defaultRecord);
                this.Save();
            }

            return defaultRecord;
        }

        public void Add(Signatory signatory)
        {
            _signatoryRepository.Add(signatory);
        }

        public void Update(Signatory signatory)
        {
            _signatoryRepository.Update(signatory);
        }

        public void Delete(int id)
        {
            var signatory = GetById(id);
            if (signatory != null)
                _signatoryRepository.Delete(signatory);
        }

        public bool Save()
        {
            string message;
            _signatoryRepository.Save(out message);
            return message == "Saved";
        }
    }
}
